//
//  ESTAppVersionModel.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/22.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTAppVersionModel.h"
#define AppVersion_Decimal    100
@implementation ESTAppVersionModel
+ (NSDictionary *)mj_replacedKeyFromPropertyName{
    return @{@"app_name" : @"APP_NAME"};
}
/**
 版本检测
 */
+ (void)checkAppVersionWithComplement:(void(^)(void))complement {
    BaseInfo.app_id = APP_ID_2;
    [NetTool checkAppVersionCompelment:^(NSArray *result) {
        BaseInfo.app_id = APP_ID_1;
        if (result) {
            NSMutableArray *arrM = [ESTAppVersionModel mj_objectArrayWithKeyValuesArray:result];
            ESTAppVersionModel *model = arrM.firstObject;
            if ([self comareVersion:model.VERSION_NO]) {
                if ([model.MANDATORY_UPGRADE integerValue] == 1) {
                    [TYZSystemDialog dialogWithTitle:[@"发现新版本，您必须更新才能继续使用。谢谢您的配合！\n点击确认，立即跳转" S] dialogType:SystemDialogType_Destructive_Center complement:^{
                        [[TYZApplication sharedApplication] openURL:[NSURL URLWithString:model.APP_DESC]];
                    }];
                } else {
                    [TYZSystemDialog dialogWithTitle:[@"发现新版本，是否立即更新？" S] complement:^{
                        [[TYZApplication sharedApplication] openURL:[NSURL URLWithString:model.APP_DESC]];
                    }];
                }
            } else {
                if (complement) {
                    complement();
                }
            }
        } else {
            if (complement) {
                complement();
            }
        }
    }];
}

/**
 比较版本号

 @param version 服务器返回的版本
 @return 是否需要升级
 */
+ (BOOL)comareVersion:(NSString *)version {
    long long value1 = [self valueFromVersion:CoreInfo.app_version];
    long long value2 = [self valueFromVersion:version];
    return value1 < value2;
}
+ (long long)valueFromVersion:(NSString *)version {
    NSArray<NSString *> *arr = [version componentsSeparatedByString:@"."];
    __block long long value = 0;
    [arr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger integer = [obj integerValue];
        integer = integer * pow(AppVersion_Decimal, arr.count - 1 - idx);
        value += integer;
    }];
    return value;
}
@end
